from django.conf import settings
from django.db.models import get_model
from django.contrib import admin
from django.contrib.auth.models import User
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.forms import UserChangeForm
from django import forms

import multiprofiles.utils as utils
import inlines

UserModel = utils.get_user_class()

class ProfileSelect(forms.Select):
    class Media:
        js = ('multiprofiles/profile_select.js', )


class CustomUserChangeForm(UserChangeForm):
    class Meta:
        model = UserModel
        widgets = {
            'profile_type': ProfileSelect(),
        }


class UserProfileAdmin(UserAdmin):

    profile_inlines = inlines.ProfileInlinesManager.get_inline_classes()

    list_filter = UserAdmin.list_filter + ('profile_type',)
    form = CustomUserChangeForm

    fieldsets = UserAdmin.fieldsets
    fieldsets[0][1]['fields'] = fieldsets[0][1]['fields'] + ('profile_type',)

    add_fieldsets = UserAdmin.add_fieldsets
    add_fieldsets[0][1]['fields'] = add_fieldsets[0][1]['fields'] + ('profile_type',)


    def get_formsets(self, request, obj=None):
        if obj:
            profile_inline = self.inline_profile_instances[obj.profile_type]
            self.inline_instances.append(profile_inline)
            self._previous_profile = profile_inline
        for inline in self.inline_instances:
            yield inline.get_formset(request, obj)
    
    def get_inline_instances(self, request, obj=None):
        self.inline_instances = super(UserProfileAdmin, self).get_inline_instances(request)
        try:
            self.inline_instances.remove(self._previous_profile)
        except ValueError:
            pass
        return self.inline_instances
    
    def __init__(self, model, admin_site):
        self._previous_profile = None
        self.inline_profile_instances = {}
        for (profile_type, profile_class) in self.profile_inlines.items():
            profile_instance = profile_class(model, admin_site)
            self.inline_profile_instances[profile_type] = profile_instance
        super(UserProfileAdmin, self).__init__(model, admin_site)


admin.site.unregister(User)
admin.site.register(UserModel, UserProfileAdmin)

del UserModel